package com.java.example.util.wxutil

import android.content.Context
import android.graphics.Bitmap
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXImageObject
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage.IMediaObject
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject
import com.tencent.mm.opensdk.modelmsg.WXTextObject
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.java.example.app.AccountManager.currentUser
import java.io.ByteArrayOutputStream

class WeChatShareUtil {
    //IWXAPI是第三方app和微信通信的openapi接口
    private var api: IWXAPI? = null
    private var context: Context? = null

    //注册应用id到微信
    private fun regToWx() {
        //通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(context, APP_ID, true)
        //将应用的appId注册到微信
        api?.registerApp(APP_ID)
    }

    /**
     * 分享文字到朋友圈或者好友
     *
     * @param text  文本内容
     * @param scene 分享方式：好友还是朋友圈
     */
    fun shareText(text: String, scene: Int): Boolean {
        //初始化一个WXTextObject对象，填写分享的文本对象
        val textObj = WXTextObject()
        textObj.text = text
        return share(textObj, text, scene)
    }

    /**
     * 分享图片到朋友圈或者好友
     *
     * @param bmp   图片的Bitmap对象
     * @param scene 分享方式：好友还是朋友圈
     */
    fun sharePic(bmp: Bitmap, scene: Int): Boolean {
        //初始化一个WXImageObject对象
        val imageObj = WXImageObject(bmp)
        //设置缩略图
        val thumb = Bitmap.createScaledBitmap(bmp, 60, 60, true)
        bmp.recycle()
        return share(imageObj, thumb, scene)
    }

    /**
     * 分享网页到朋友圈或者好友，视频和音乐的分享和网页大同小异，只是创建的对象不同。
     * 详情参考官方文档：
     * https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419317340&token=&lang=zh_CN
     *
     * @param url         网页的url
     * @param title       显示分享网页的标题
     * @param description 对网页的描述
     * @param scene       分享方式：好友还是朋友圈
     */
    fun shareUrl(url: String?, title: String?, thumb: Bitmap?, description: String?, scene: Int): Boolean {
        //初试话一个WXWebpageObject对象，填写url
        val webPage = WXWebpageObject()
        webPage.webpageUrl = url
        return share(webPage, title, thumb, description, scene)
    }

    private fun share(mediaObject: IMediaObject, thumb: Bitmap, scene: Int): Boolean {
        return share(mediaObject, null, thumb, null, scene)
    }

    private fun share(mediaObject: IMediaObject, description: String, scene: Int): Boolean {
        return share(mediaObject, null, null, description, scene)
    }

    private fun share(mediaObject: IMediaObject, title: String?, thumb: Bitmap?, description: String?, scene: Int): Boolean {
        //初始化一个WXMediaMessage对象，填写标题、描述
        val msg = WXMediaMessage(mediaObject)
        if (title != null) {
            msg.title = title
        }
        if (description != null) {
            msg.description = description
        }
        if (thumb != null) {
            msg.thumbData = bmpToByteArray(thumb, true)
        }
        //构造一个Req
        val req = SendMessageToWX.Req()
        req.transaction = System.currentTimeMillis().toString()
        req.message = msg
        req.scene = scene
        return api!!.sendReq(req)
    }


    fun shareMini(bmp: Bitmap) {
        //分享小程序
        val miniProgramObj = WXMiniProgramObject()
        miniProgramObj.webpageUrl = "https://www.zcjc.vip/" // 不能为空，为空就不能发起分享
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPROGRAM_TYPE_PREVIEW // 正式版:0，测试版:1，体验版:2
        miniProgramObj.userName = "gh_39205b146d13" // 小程序原始id
        miniProgramObj.path = "pages/index/index?phone=" + currentUser!!.phone //小程序页面路径；对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"
        val msg = WXMediaMessage(miniProgramObj)
        msg.title = "旺材" // 小程序消息title
        //        msg.description = "旺材2";               // 小程序消息desc
        msg.thumbData = bmpToByteArray(bmp, true) // 小程序消息封面图片，小于128k
        val req = SendMessageToWX.Req()
        req.transaction = System.currentTimeMillis().toString()
        req.message = msg
        req.scene = SendMessageToWX.Req.WXSceneSession // 目前只支持会话
        api!!.sendReq(req)
    }

    fun launchMini() {
        //拉起小程序
        val req = WXLaunchMiniProgram.Req()
        req.userName = "gh_39205b146d13" // 填小程序原始id
        req.path = "pages/index/index?phone=" + currentUser!!.phone ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW // 可选打开 开发版，体验版和正式版
        api!!.sendReq(req)
    }


    val isSupportWX: Boolean
        //判断是否支持转发到朋友圈
        get() {
            val wxSdkVersion = api!!.wxAppSupportAPI
            return wxSdkVersion >= TIMELINE_SUPPORTED_VERSION
        }

    private fun bmpToByteArray(bmp: Bitmap, needRecycle: Boolean): ByteArray {
        val output = ByteArrayOutputStream()
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output)
        if (needRecycle) {
            bmp.recycle()
        }
        val result = output.toByteArray()
        try {
            output.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return result
    }

    companion object {
        //从官网申请的合法appId
        const val APP_ID: String = "wxc5baebdbe12d3217"
        private const val TIMELINE_SUPPORTED_VERSION = 0x21020001

        var weChatShareUtil: WeChatShareUtil? = null

        fun getInstance(context: Context?): WeChatShareUtil? {
            if (weChatShareUtil == null) {
                weChatShareUtil = WeChatShareUtil()
            }
            if (weChatShareUtil!!.api != null) {
                weChatShareUtil!!.api!!.unregisterApp()
            }
            weChatShareUtil!!.context = context
            weChatShareUtil!!.regToWx()
            return weChatShareUtil
        }
    }
}
